﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Common.StringTools
{
    public static class StringGenerator
    {
        ///<summary>
        ///生成随机字符串
        ///</summary>
        ///<param name="length">目标字符串的长度</param>
        ///<param name="withNum">是否包含数字</param>
        ///<param name="withLower">是否包含小写字母</param>
        ///<param name="withUpper">是否包含大写字母</param>
        ///<param name="withSpe">是否包含特殊字符，1=包含，默认为不包含</param>
        ///<param name="byCustom">要包含的自定义字符，直接输入要包含的字符列表</param>
        ///<returns>指定长度的随机字符串</returns>
        public static string GetRnd(int length, bool withNum, bool withLower, bool withUpper, bool withSpe, string byCustom = "")
        {
            byte[] b = new byte[4];
            new System.Security.Cryptography.RNGCryptoServiceProvider().GetBytes(b);
            Random r = new Random(BitConverter.ToInt32(b, 0));

            string s = null, str = byCustom;

            if (withNum == true) { str += "0123456789"; }
            if (withLower == true) { str += "abcdefghijklmnopqrstuvwxyz"; }
            if (withUpper == true) { str += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; }
            if (withSpe == true) { str += "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"; }

            for (int i = 0; i < length; i++)
                s += str.Substring(r.Next(0, str.Length - 1), 1);

            return s;
        }
    }
}
